package com.huluobo.a2202kotlindouyindemo.video

import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.EditText
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2202kotlindouyindemo.R
import com.huluobo.a2202kotlindouyindemo.adapter.CommentAdapter
import com.huluobo.a2202kotlindouyindemo.adapter.MultiVideoAdapter
import com.huluobo.a2202kotlindouyindemo.databinding.FragmentVideoBinding
import com.huluobo.a2202kotlindouyindemo.live.LiveActivity
import com.huluobo.a2202kotlindouyindemo.login.LoginActivity
import com.huluobo.base.bean.CommentBean
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMFragment
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb

class VideoFragment : BaseMVVMFragment<FragmentVideoBinding>() {
    private lateinit var viewModel: VideoViewModel

    private lateinit var videoAdapter: MultiVideoAdapter

    var currentPosition: Int = 0

    lateinit var player: StandardGSYVideoPlayer

    private lateinit var commentAdapter: CommentAdapter

    private val commentList = mutableListOf<CommentBean>()

    override fun getLayoutId(): Int = R.layout.fragment_video

    override fun initData() {
        viewModel = ViewModelProvider(this)[VideoViewModel::class.java]

        viewModel.getVideoList(1, 10)

        viewModel.getVideoListSuccess.observe(this) {
            if (it.code == 200) {
                videoAdapter.data.clear()
                videoAdapter.data.addAll(it.data)
                videoAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getVideoListFailed.observe(this) {
            Log.i("TagA", "获取视频列表失败:$it")
        }

        viewModel.likeVideoSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                videoAdapter.data[currentPosition].dianzan = 1
                videoAdapter.notifyDataSetChanged()
            }
        }

        viewModel.likeVideoFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.noLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                videoAdapter.data[currentPosition].dianzan = 0
                videoAdapter.notifyDataSetChanged()
            }
        }

        viewModel.noLikeVideoFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                videoAdapter.data[currentPosition].guanzhu = 1
                videoAdapter.notifyDataSetChanged()
            }
        }

        viewModel.followAuthFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.getCommentSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                commentList.clear()
                commentList.addAll(it.data)
                commentAdapter.notifyDataSetChanged()
            }
        }

        viewModel.getCommentFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.sendCommentSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                commentAdapter.data.addAll(0, it.data)
                commentAdapter.notifyDataSetChanged()

                val editText = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_input_et) as EditText
                editText.text.clear()
            }
        }

        viewModel.sendCommentFailed.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.followSuccess.observe(this) {
            ToastUtils.showLong(it)
        }

        viewModel.followFailed.observe(this) {
            ToastUtils.showLong(it)
        }
    }

    override fun initView() {
        val layoutManager = LinearLayoutManager(requireContext())
        dataBinding.videoRv.layoutManager = layoutManager
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(dataBinding.videoRv)
        videoAdapter = MultiVideoAdapter()
        dataBinding.videoRv.adapter = videoAdapter

        dataBinding.videoRv.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取当前展示的item的下标
                currentPosition = layoutManager.findFirstVisibleItemPosition()

                //通过adapter的position拿到对应的播放器
                player =
                    videoAdapter.getViewByPosition(currentPosition, R.id.item_video_gsyPlayer) as StandardGSYVideoPlayer
                //自动播放,实现原理 当RecyclerView滑动的时候,找到对应的显示的item,然后获取到播放器让他播放
//                player.startPlayLogic()
            }
        })

        //添加adapter中的view的点击事件
        videoAdapter.addChildClickViewIds(
            R.id.item_video_like_iv,
            R.id.item_video_add_iv,
            R.id.item_video_comment_iv,
            R.id.item_video_close_iv,
            R.id.item_video_send_iv,
            R.id.item_video_follow_iv,
            R.id.item_video_share_iv,
            R.id.item_video_full_cl,
            R.id.item_video_live_cl
        )

        //设置item中view的点击事件
        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            //拿到对应item位置的video实体类
            val videoBean = adapter.data[position] as VideoBean
            if (isLoggedInBefore()) {
                when (view.id) {
                    R.id.item_video_like_iv -> likeVideo(videoBean)
                    R.id.item_video_add_iv -> followAuth(videoBean)
                    R.id.item_video_comment_iv -> openComment(videoBean)
                    R.id.item_video_close_iv -> closeComment()
                    R.id.item_video_send_iv -> sendComment(videoBean)
                    R.id.item_video_follow_iv -> followVideo(videoBean)
                    R.id.item_video_share_iv -> shareVideo(videoBean)
                    R.id.item_video_live_cl -> toLiveRoom(videoBean)
                    R.id.item_video_full_cl -> fullScreen()
                }
            } else {
                ToastUtils.showLong("请先登录")
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
            }

        }
    }

    private fun fullScreen() {
        player.isRotateViewAuto = true
        player.startWindowFullscreen(requireContext(), false, false)
    }

    private fun toLiveRoom(videoBean: VideoBean) {
        val intent = Intent(requireContext(), LiveActivity::class.java)
        intent.putExtra("videoBean", videoBean)
        startActivity(intent)
    }

    private fun shareVideo(videoBean: VideoBean) {
        val umImage = UMImage(requireContext(), videoBean.videomainimg)
        umImage.compressStyle = UMImage.CompressStyle.SCALE

        val umWeb = UMWeb(videoBean.videopath)
        umWeb.title = videoBean.authname
        umWeb.setThumb(umImage)
        umWeb.description = videoBean.caption

        ShareAction(requireActivity())
            .withMedia(umWeb)
            .open()
    }

    private fun isLoggedInBefore(): Boolean {
        return !TextUtils.isEmpty(SPUtils.getInstance().getString(Const.PARAM_TOKEN))
    }

    //收藏视频
    private fun followVideo(videoBean: VideoBean) {
        viewModel.followVideo(videoBean)
    }

    //发送评论
    private fun sendComment(videoBean: VideoBean) {
        val editText = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_input_et) as EditText
        val sendMessage = editText.text.toString().trim()
        if (!TextUtils.isEmpty(sendMessage)) {
            viewModel.sendComment(sendMessage, videoBean.id)
        } else {
            ToastUtils.showLong("请输入评论内容")
        }
    }

    //关闭评论列表
    private fun closeComment() {
        val commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll)
        if (commentLayout != null) {
            val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
            animOut.duration = 500
            animOut.interpolator = AccelerateInterpolator()
            animOut.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    commentLayout.visibility = View.GONE
                    dataBinding.videoRv.setIntercept(true)
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animOut)
        }
    }

    //打开评论列表
    private fun openComment(videoBean: VideoBean) {
        dataBinding.videoRv.setIntercept(false)
        val commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll)
        if (commentLayout != null) {
            commentLayout.visibility = View.VISIBLE
            //加载动画
            val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
            animIn.duration = 500
            animIn.interpolator = AccelerateInterpolator()
            animIn.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                    viewModel.getComments(videoBean.id)
                }

                override fun onAnimationEnd(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animIn)

            val commentRv: RecyclerView =
                videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_rv) as RecyclerView
            commentRv.layoutManager = LinearLayoutManager(requireContext())
            commentAdapter = CommentAdapter(commentList)
            commentRv.adapter = commentAdapter
        }
    }

    private fun followAuth(videoBean: VideoBean) {
        viewModel.followAuth(videoBean.authname)
    }

    //点赞和取消点赞方法
    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.dianzan == 0) {
            //未点赞,触发点赞方法
            viewModel.likeVideo(videoBean.id)
        } else {
            //一点赞,触发取消点赞方法
            viewModel.noLikeVideo(videoBean.id)
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.getVideoList(1, 10)
    }
}